package com.yulebaby.callsenter.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.logger.Logger;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.CustomerInSeaAdapter;
import com.yulebaby.callsenter.adapter.selectadpter.DateLeftAdapter;
import com.yulebaby.callsenter.adapter.selectadpter.DateRightAdapter;
import com.yulebaby.callsenter.adapter.selectadpter.DropDownAdapter;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.FindCustomerInSeaBean;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.http.callback.ResultCallback;
import com.yulebaby.callsenter.task.RequestInternationalWatersCustomerTask;
import com.yulebaby.callsenter.task.UploadCustomerTask;
import com.yulebaby.callsenter.ui.activity.AddPreSaleRemarkActivity;
import com.yulebaby.callsenter.ui.activity.CustomerInfoActivity;
import com.yulebaby.callsenter.ui.activity.CustomerSearchActivity;
import com.yulebaby.callsenter.ui.base.BaseFragment;
import com.yulebaby.callsenter.ui.view.CustomPopwindow;
import com.yulebaby.callsenter.ui.view.RobCustomerDialog;
import com.yulebaby.callsenter.ui.view.StateViewLayout;
import com.yulebaby.callsenter.ui.view.YuLeBaByDropDownMenu;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.CommonUtil;
import com.yulebaby.callsenter.utils.DateUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zhangbo on 2016/12/25.
 */

public class InternationalWaterFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, StateViewLayout.OnReloadBtnClickListener {

    @BindView(R.id.iv_search)
    ImageView mIvSearch;
    @BindView(R.id.ylbb_ddmenu)
    YuLeBaByDropDownMenu mYlbbDdmenu;

    public ArrayList<CustomerBean> customerinSeaList = new ArrayList<>();
    private StateViewLayout mStateViewLayout;
    private CustomerInSeaAdapter mAdapter = new CustomerInSeaAdapter(customerinSeaList);
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefresh;
    private boolean isRefresh;

    private String headers[] = {"信息来源", "建档时间", "归属区域"};
    private String mMonthAll[] = {"全部公海客户"};
    private String[] mAddress, mFrom, mBuilderMonth;
    private ArrayList<String> mBuilderYear;
    private List<View> popupViews = new ArrayList<>();
    private int constellationPosition = 0;
    private int leftSelectPosition = 0;

    private DropDownAdapter addressAdapter, dateAdapter, fromAdapter;
    private View mView;

    private int datanum = 0;

    private CustomerBean mCustomerBean;
    /**
     * 是否是加载更多
     */
    private boolean isLoadMore = false;
    private CustomPopwindow mCustomPopwindow;
    private RobCustomerDialog mRobDialogSuccess;
    private RobCustomerDialog mRobDialogFail;
    private View mRootFragment, mLayoutInsea;
    private ListView mLvLeft, mLvRight;
    private DateLeftAdapter mLeftAdapter;
    private DateRightAdapter mRightAdapter;
    private FindCustomerInSeaBean findBean;
    private LayoutInflater mInflater;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mInflater = LayoutInflater.from(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_international_waters, container, false);
        if (mStateViewLayout == null) {
            mStateViewLayout = new StateViewLayout(mActivity);
            mStateViewLayout.setSuccessView(getSuccessView());
            mStateViewLayout.showLoadingView();
            mStateViewLayout.setOnReloadClickListener(this);
            requestData();
        } else {
            ViewGroup parent = (ViewGroup) mStateViewLayout.getParent();
            if (parent != null) {
                parent.removeView(mStateViewLayout);
            }
        }
        ButterKnife.bind(this, layout);
        return layout;
    }

    public static InternationalWaterFragment newInstance() {
        Bundle args = new Bundle();
        InternationalWaterFragment fragment = new InternationalWaterFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @OnClick(R.id.iv_search)
    public void onClick() {
        //跳转到查询的界面
        Intent intent = new Intent(mActivity, CustomerSearchActivity.class);
        intent.putExtra(Constant.CLASS_NAME, false);
        startActivity(intent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mRobDialogSuccess != null && mRobDialogSuccess.isShowing()) {
            mRobDialogSuccess.dismiss();
        }
        if (mRobDialogFail != null && mRobDialogFail.isShowing()) {
            mRobDialogFail.dismiss();
        }
        if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
            mCustomPopwindow.dismiss();
        }
    }

    /**
     * 成功的View
     *
     * @return
     */
    public View getSuccessView() {
        mLayoutInsea = mInflater.inflate(R.layout.layout_customer_insea, null);
        mRecyclerView = (RecyclerView) mLayoutInsea.findViewById(R.id.base_recycleview);
        mSwipeRefresh = (SwipeRefreshLayout) mLayoutInsea.findViewById(R.id.base_refresh);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new YuLeBaByLinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        initRefresh();
        return mLayoutInsea;
    }

    public void requestData() {
        RequestInternationalWatersCustomerTask.doRequestInternationalWatersTask(mActivity, findBean, isLoadMore ? datanum : 0, new ResultCallback<List<CustomerBean>>() {
            @Override
            public void onResult(List<CustomerBean> result) {
                if (result.size() < 20) {
                    mAdapter.setEnableLoadMore(false);
                } else {
                    mAdapter.setEnableLoadMore(true);
                }
                processResult(result);
            }
        });
    }

    //下拉刷新
    private void initRefresh() {
        mSwipeRefresh.setOnRefreshListener(this);
        mSwipeRefresh.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);
    }

    /**
     * 处理结果
     *
     * @param result
     */

    private void processResult(List<CustomerBean> result) {
        if (isLoadMore) {
            if (result.size() > 0) {
                mAdapter.addData(result);
                mAdapter.loadMoreComplete();
                isLoadMore = false;
            } else {
                mAdapter.loadMoreFail();
            }
        } else {
            customerinSeaList.clear();
            if (result.size() > 0) {
                customerinSeaList.addAll(result);
                mStateViewLayout.showSuccessView();
            } else {
                mStateViewLayout.showErrorView();
            }
//        // 有潜在异常
//        mAdapter.setNewData(mCustomerlist);
            mAdapter.notifyDataSetChanged();
            if (isRefreshing()) {
                refreshComplete();
            }
        }
    }


    protected boolean isRefreshing() {
        return isRefresh;
    }

    protected void refreshComplete() {
        mSwipeRefresh.setRefreshing(false);
        isRefresh = false;
    }

    @Override
    public void onRefresh() {
        mSwipeRefresh.setRefreshing(true);
        isRefresh = true;
        requestData();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initData();
        initView();
        findBean = new FindCustomerInSeaBean(); // 筛选用的Bean
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.setEnableLoadMore(true);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                //使用Intent的方式  使用消息总线的方式改进  粗糙版本
                Intent intent = new Intent(mActivity, CustomerInfoActivity.class);
                intent.putExtra(Constant.CUSTOMER_BEAN, (CustomerBean) baseQuickAdapter.getItem(position));
                intent.putExtra(Constant.IS_MODIFY, false);
                startActivity(intent);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mCustomerBean = (CustomerBean) baseQuickAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.iv_robcustomer:
                        robCustomers(view, mCustomerBean, position);
                        break;
                    case R.id.tv_looktrack:
                        if (mCustomerBean != null) {
                            initCustomPopwindow(view);
                        }
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 初始化Popwindow
     *
     * @param view
     */
    private void initCustomPopwindow(View view) {
        mCustomPopwindow = new CustomPopwindow(mActivity, itemsOnClick, mCustomerBean);
        mCustomPopwindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    //为弹出窗口内部实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            mCustomPopwindow.backgroundAlpha(mActivity, 1f);
            switch (v.getId()) {
                case R.id.ib_cancal:
                    if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
                        mCustomPopwindow.dismiss();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 抢客户
     *
     * @param view
     * @param customer
     * @param position
     */
    private void robCustomers(View view, final CustomerBean customer, final int position) {
        UploadCustomerTask.doRobCustomer(mActivity, customer.getCustomer_id(), new HttpCallback<ResultBean>() {
            @Override
            public void onSuccessResultNull() {
                mRobDialogSuccess = new RobCustomerDialog(mActivity, true, new RobCustomerDialog.DialogCallBack() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        mAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                        Intent addintent = new Intent(mActivity, AddPreSaleRemarkActivity.class);
                        addintent.putExtra(Constant.CUSTOMER_BEAN, customer);
                        startActivity(addintent);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        mAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                    }
                });
                mRobDialogSuccess.show();
                EventBus.getDefault().post(EventFactory.CreateRefreshEvent(RefreshEvent.refreshDataFromInternet));
            }

            @Override
            public void onFailParam(String info) {
                super.onFailParam(info);
                mRobDialogFail = new RobCustomerDialog(mActivity, false, new RobCustomerDialog.DialogCallBack() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        mAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                    }
                });
                mRobDialogFail.show();
            }
        });
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        datanum = mAdapter.getData().size();
        isLoadMore = true;
        requestData();
    }

    @Override
    public void onReloadBtnClick() {
        mStateViewLayout.showLoadingView();
        requestData();
    }

    /**
     * 第三方使用ListView RecycleView的item高度有问题 暂保持listVIew
     * 时间太紧,维护的时候小心点吧
     */
    private void initView() {
        /**
         * 归属区域
         */
        final ListView addressView = new ListView(mActivity);
        addressView.setDividerHeight(0);
        addressView.setVerticalScrollBarEnabled(false);
        addressView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        addressAdapter = new DropDownAdapter(mActivity, Arrays.asList(mAddress));
        addressView.setAdapter(addressAdapter);
        /**
         * 归属区域的选择逻辑
         */
        addressView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
                    addressAdapter.setCheckItem(position);
                    mYlbbDdmenu.setTabText(position == 0 ? headers[2] : mAddress[position]);
                    mYlbbDdmenu.closeMenu();
                    findBean.setCustomerTypeName(position == 0 ? null : mAddress[position]);
                    requestData();
                }
        );

        /**
         * 信息来源
         */
        final ListView fromView = new ListView(mActivity);
        fromView.setDividerHeight(0);
        fromView.setVerticalScrollBarEnabled(false);
        fromView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        fromAdapter = new DropDownAdapter(mActivity, Arrays.asList(mFrom));
        fromView.setAdapter(fromAdapter);
        /**
         * 信息来源的选择逻辑
         */
        fromView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
                    fromAdapter.setCheckItem(position);
                    mYlbbDdmenu.setTabText(position == 0 ? headers[0] : mFrom[position]);
                    mYlbbDdmenu.closeMenu();
                    findBean.setCustomerBaseChannel(position == 0 ? null : mFrom[position]);
                    requestData();
                }
        );

        View selectDate = LayoutInflater.from(mActivity).inflate(R.layout.layout_select_date, null);

        mLvLeft = (ListView) selectDate.findViewById(R.id.lv_left);
        mLvRight = (ListView) selectDate.findViewById(R.id.lv_right);

        mLvRight.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mLvLeft.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mLvLeft.setVerticalScrollBarEnabled(false);
        mLvRight.setVerticalScrollBarEnabled(false);

        mLvRight.setDividerHeight(0);
        mLvLeft.setDividerHeight(0);

        mLeftAdapter = new DateLeftAdapter(mActivity, mBuilderYear);
        // 默认选中第一个选项
        mLvLeft.setSelection(0);
        // 建立数据适配
        mLvLeft.setAdapter(mLeftAdapter);

        // 设置listView当中的每个单项点击的事件变化逻辑处理
        mLvLeft.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
                    leftSelectPosition = position;
                    // 主目录一位数组的大小和侧目录二维数组的行的数目是一致的
                    // 点击传入二维数组的一行的数据
                    inintAdapter(position == 0 ? mMonthAll : mBuilderMonth);
                    // 设置选中的选的id
                    mLeftAdapter.setSelectItem(position);
                    // 更新数据的变更
                    mLeftAdapter.notifyDataSetChanged();
                }
        );

        /**
         * CHOICE_MODE_NONE是普通模式，
         * CHOICE_MODE_SINGLE是单选模式，
         * CHOICE_MODE_MULTIPLE和CHOICE_MODE_MULTIPLE_MODAL都是多选模式
         *
         * 设置选着的模式
         * */
        mLvLeft.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        // 设置还没有点击时默认的显示页面的内容
        inintAdapter(mMonthAll);

        // 二级界面地点击逻辑
        mLvRight.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
                    mYlbbDdmenu.setTabText(position == 0 ? leftSelectPosition == 0 ? headers[1] : mBuilderYear.get(leftSelectPosition) + "年" : mBuilderYear.get(leftSelectPosition) + "年—" + mBuilderMonth[position]);
                    mYlbbDdmenu.closeMenu();
                    String time = mBuilderYear.get(leftSelectPosition) + mBuilderMonth[position].replace("月", "").replaceAll("全部", "");
                    findBean.setYearMonthObj(mBuilderYear.get(leftSelectPosition).trim().equals("全部") ? "" : time);
                    requestData();
                }
        );

        popupViews.add(fromView);
        popupViews.add(selectDate);
        popupViews.add(addressView);

        mYlbbDdmenu.setDropDownMenu(Arrays.asList(headers), popupViews, mStateViewLayout);

    }

    // 为侧目录(详细目录)进行数据的匹配处理
    private void inintAdapter(String[] array) {
        mRightAdapter = new DateRightAdapter(mActivity, array);
        mLvRight.setAdapter(mRightAdapter);
        mRightAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化选项数据
     */
    private void initData() {
        mBuilderYear = new ArrayList<>();
        mAddress = CommonUtil.getStringArray(R.array.select_address);

        mFrom = CommonUtil.getStringArray(R.array.select_from);
        for (int i = DateUtil.getCurrentYear(); i >= 2012; i--) {
            mBuilderYear.add(String.valueOf(i));
        }
        mBuilderMonth = CommonUtil.getStringArray(R.array.build_month);
        mBuilderYear.add(0, "全部");
    }
}
